import langStr from "./zh-CN.js";
import fs from "fs";

let pkey = process.argv.slice(2);
let path = "";

for (let i = 0; i < pkey.length; i++) {
  if (pkey[i].includes("path=")) {
    //获取需要替换文本的文件路径
    path = pkey[i].split("=")[1].trim();
    pkey.splice(i, 1);
  }
}

let ws = fs.createWriteStream("./t.txt", {
  flags: "w",
  encoding: "utf-8",
  autoClose: true,
});

let tobj = {};
function parset(obj, parent) {
  for (let key in obj) {
    let p = parent ? parent + "." + key : key;
    if (typeof obj[key] == "object") {
      let k = parent ? p : key;
      parset(obj[key], k);
    } else {
      let str = parent ? p : key;
      let s = eval("langStr." + str);
      tobj[s] = `t('${str}')`;
    }
  }
}
if (pkey.length && pkey.length > 0) {
  for (let p of pkey) {
    parset(langStr[p], p);
  }
} else {
  parset(langStr);
}
ws.write(JSON.stringify(tobj, null, 2));
if (path) {
  let nwf = fs.createWriteStream(path, {
    flags: "w",
    encoding: "utf-8",
    autoClose: true,
  });
  let file = fs.readFileSync(path, { encoding: "utf-8" });
  let tempStr = file.match(/<template>([\s\S]*?)<\/template>/)?.[0] ?? "";
  let scrStr = file.match(/<script.*>([\s\S]*?)<\/script>/)?.[0] ?? "";
  let styStr = file.match(/<style.*>([\s\S]*?)<\/style>/)?.[0] ?? "";

  if (!tempStr && !scrStr && !styStr) {
    //其它文件
    for (let k in tobj) {
      file = file.replaceAll(`"${k}"`, tobj[k]);
    }
    nwf.write(file);
  } else {
    //.vue文件
    for (let k in tobj) {
      let reg = new RegExp(`(\\w+)=['"\s]*` + k, "g");
      let reg2 = new RegExp(`([^\u4e00-\u9fa5])${k}([^\u4e00-\u9fa5])`, "g"); //精准匹配汉字词组，防止只匹配到部分字
      tempStr = tempStr
        .replace(reg, ':$1="' + tobj[k])
        .replace(reg2, "$1{{" + tobj[k] + "}}$2");
      scrStr = scrStr.replaceAll(`"${k}"`, tobj[k]);
    }
    nwf.write(tempStr + "\n" + scrStr + "\n" + styStr);
  }
}
